package org.douxiaoban.client.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.google.gdata.data.client.DoubanService;
import com.google.gdata.data.douban.*;
import com.google.gdata.data.extensions.Rating;
import com.google.gdata.util.ServiceException;
import com.mobclick.android.MobclickAgent;
//import net.youmi.android.AdManager;
import org.douxiaoban.client.R;
import org.douxiaoban.client.api.*;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.widget.IRecommend;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

import java.io.IOException;
import java.util.*;


/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-5-28
 * Time: 下午8:48
 */
public class CollectionSubjectActivity extends BaseActivity implements IRecommend {
    private String _id;
    private String _subject_type;

    private ThreadTool _thread;
    private LinearLayout _progressLay;
    private ScrollView _scrollView;
    private SubjectRecord _subjectRecord;
    private LayoutInflater _inflater;


    //View Compent
    private TextView _titleTx;
    private LinearLayout _subjectContentLay;
    private LinearLayout _subjectReviewLay;
    private Button _recommendBtn;
    private ImageView _coverImage;
    private LinearLayout _attributeLay;
    private RatingBar _ratingbar;
    private TextView _rating_average;
    private TextView _rating_num;
    private TextView _authorSummary;
    private TextView _cotentSummary;
    private LinearLayout _tagsLay;
    private TextView _subjectMyRatingTextTx;
    private RatingBar _subjectMyRating;
    private TextView _subjectMyRatingDescTx;
    private Button _subjectPublishReviewBtn;
    private Button _subjectLoadReviewBtn;
    private Button _subjectShareBtn;

    //Collection
    private RatingBar _subjectModifyRating;
    private EditText _subjectModifyTags;
    private EditText _subject_modify_summary;
     private RadioGroup _subjectModifyStatusGroup;
    private RadioButton _subjectModifyWishRadio;
    private RadioButton _subjectModifyReadedRadio;
    private RadioButton _subjectModifyReadingRadio;
    private Button _subjectUpdateCollectionBtn;

    //Douban FM
    private LinearLayout _fmLay;
    private TextView _fmText;

    private int _subjectReviewCount = 1;

    private ArrayList<ImageView> _subjectReviewAvatarImageView
            = new ArrayList<ImageView>();
    private ArrayList<Bitmap> _subjectReviewAvatarBitmap
            = new ArrayList<Bitmap>();

    private PopupRecommend _popupRecommend;

    //评论列表数据
    private ArrayList<ReviewRecord> _reviewsList;

    private CollectionRecord _collectionRecord;
    private TitleStyle _title_style;


//    static{
//		AdManager.init(Assistant.AD_YOUMI_KEY, Assistant.AD_YOUMI_SCRET, 30, false, 0.1);
//	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.subject);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

        _title_style = new TitleStyle(this);
        _title_style.initTitleStyle();
        setupViews();
        setupIntent();
    }

    /**
     * 初始化Intnet变量,给成员变量赋值
     * getIntent 中CollectionRecord的返回为空时，表示不是从用户的收藏列表进入，
     * 根据返回的Link对象判断该条目是否是用户收藏过，如果是则重新开线程获取数据
     *
     * @see CollectionBookListActivity
     */
    private void setupIntent(){
         Intent intent = this.getIntent();
        _thread = ThreadTool.instace(this);

        _inflater = LayoutInflater.from(this);

        _id = intent.getStringExtra(Assistant.KEY_OF_INTENT_ID);
        _subject_type = intent.getStringExtra(Assistant.KEY_OF_INTENT_CATEGORY);

        TestParcelable testParcelable =  intent.getParcelableExtra("parcelable");

        if(intent.getIntExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,0)!=0){
           int ratting =intent.getIntExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,0);
           _subjectMyRating.setRating(ratting);
           int type = intent.getIntExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,1);
           _subjectMyRatingDescTx.setText(Assistant.SUBJECT_RATING_DESC.get(ratting));
            String summary = intent.getStringExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY);
            _subject_modify_summary.setText(summary);

            String tag = intent.getStringExtra(Assistant.KEY_OF_MY_SUBJECT_TAG);
            _subjectModifyTags.setText(tag);

            if(type == 1)
                _subjectModifyReadedRadio.setChecked(true);
            if(type == 2)
                _subjectModifyWishRadio.setChecked(true);
            if(type == 3)
                _subjectModifyReadingRadio.setChecked(true);
        }else{
            _subjectMyRating.setVisibility(View.GONE);
            _subjectMyRatingDescTx.setVisibility(View.GONE);
            _subjectMyRatingTextTx.setVisibility(View.GONE);
        }


        String isbn = intent.getStringExtra(Assistant.KEY_OF_ISBN);

        _popupRecommend = new PopupRecommend(this);
        _thread.startThreadFetchSubject(_id,isbn,_subject_type, _handler);

        //每个分类 读取的状态文字不是.看过,读过，听过
        modifyCollectionStatusRadio();


    }

    /**
     * 初始化布局组件，设置对应的监听事件
     */
    private void setupViews() {
        _progressLay = (LinearLayout) this.findViewById(R.id.subject_progress);
        _subjectContentLay = (LinearLayout) this.findViewById(R.id.subject_content_lay);

        _titleTx = (TextView) findViewById(R.id.subject_title);
        _attributeLay = (LinearLayout) findViewById(R.id.subject_attribute_lay);
        _coverImage = (ImageView) findViewById(R.id.subject_cover_image);
        _ratingbar = (RatingBar) findViewById(R.id.subject_rating);
        _rating_average = (TextView) findViewById(R.id.subject_rating_average);
        _rating_num = (TextView) findViewById(R.id.subject_rating_num);
        _authorSummary = (TextView) findViewById(R.id.subject_author_summary);
        _cotentSummary = (TextView) findViewById(R.id.subject_content_summary);
        _tagsLay = (LinearLayout) findViewById(R.id.subject_content_tags);
        _recommendBtn = (Button) findViewById(R.id.subject_recommend_btn);
        _progressLay = (LinearLayout)findViewById(R.id.subject_progress);
        _subjectReviewLay = (LinearLayout)findViewById(R.id.subject_review_lay);
        _subjectPublishReviewBtn = (Button)findViewById(R.id.subject_publish_review_btn);
        _subjectLoadReviewBtn = (Button)findViewById(R.id.subject_load_review_btn);
        _subjectShareBtn = (Button)findViewById(R.id.subject_share_btn);
        _subject_modify_summary = (EditText)findViewById(R.id.subject_modify_summary);

        //collection
        _subjectModifyRating = (RatingBar)findViewById(R.id.subject_modify_rating);
        _subjectModifyTags = (EditText)findViewById(R.id.subject_modify_tags);
        _subjectModifyReadedRadio = (RadioButton)findViewById(R.id.subject_modify_radio_readed);
        _subjectModifyReadingRadio = (RadioButton)findViewById(R.id.subject_modify_radio_reading);
        _subjectModifyWishRadio = (RadioButton)findViewById(R.id.subject_modify_radio_wish);
        _subjectUpdateCollectionBtn = (Button)findViewById(R.id.subject_modify_confim_btn);
        _subjectModifyStatusGroup = (RadioGroup)findViewById(R.id.subject_modify_radio_group);

        final TextView subjectModifyRatingDesc = (TextView)findViewById(R.id.subject_modify_rating_desc);

        _subjectModifyRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
            int p = (int)v;
            if(p!=0)
            subjectModifyRatingDesc.setText(Assistant.SUBJECT_RATING_DESC.get(p));
            }
        });


        //my rating
        _subjectMyRating = (RatingBar)findViewById(R.id.subject_my_rating);
        _subjectMyRatingTextTx = (TextView)findViewById(R.id.subject_my_rating_text);
        _subjectMyRatingDescTx = (TextView)findViewById(R.id.subject_my_rating_desc);

        //载入默认封面图片,加入倒影效果
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.default_book_icon_big);
        bitmap = createReflectedImage(bitmap);
        _coverImage.setImageBitmap(bitmap);

        //提交推荐
        _recommendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 _popupRecommend = new PopupRecommend(CollectionSubjectActivity.this);
                _popupRecommend.showRecommendWindow(view,
                        CollectionSubjectActivity.this, _subjectRecord.title);
            }
        });

        //发布评论
        _subjectPublishReviewBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
              _popupRecommend.showToashPublishReview(_subjectRecord.title, CollectionSubjectActivity.this);
            }
        });

        //加载评论
        _subjectLoadReviewBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //开始加载评论
                _thread.startThreadFetchSubjectReviews(_handler,_subjectRecord.id,
                                        _subjectReviewCount,_subject_type);
                _subjectLoadReviewBtn.setText("正在加载评论..");
            }
        });

        final Intent intent = new Intent(Intent.ACTION_SEND);
        //发布分享
        _subjectShareBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT,"分享");
                intent.putExtra(Intent.EXTRA_TEXT,"推荐 "+ _subjectRecord.title+
                        " " +_subjectRecord.subject_url+"-来自豆瓣(www.douban.com)");
                startActivity(Intent.createChooser(intent,getTitle()));
            }
        });

        //更新评价
        _subjectUpdateCollectionBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
              updateUserCollection();
            }
        });


    }

    private void modifyCollectionStatusRadio(){

        TextView subject_item_comment =
                (TextView)findViewById(R.id.subject_item_comment);


        if(_subject_type.equals(Assistant.STATUS_MOVICE)){
            _subjectModifyReadedRadio.setText("看过");
            _subjectModifyReadingRadio.setText("想看");
            subject_item_comment.setText("影评");
            _subjectPublishReviewBtn.setText("发表新影评");
            _subjectModifyReadingRadio.setVisibility(View.GONE);
        }else if(_subject_type.equals(Assistant.STATUS_MUSIC)){
            _subjectPublishReviewBtn.setText("发表新音评");
            subject_item_comment.setText("音评");
            _subjectModifyReadedRadio.setText("听过");
            _subjectModifyReadingRadio.setText("在听");
            _subjectModifyWishRadio.setText("想听");
        }
    }

    /**
     * 修改条目评价数据
     */
    private void updateUserCollection(){
       int rating = (int)_subjectModifyRating.getRating();
       String tags = _subjectModifyTags.getText().toString();
       int statusID = _subjectModifyStatusGroup.getCheckedRadioButtonId();
       String summary  = _subject_modify_summary.getText().toString();
       String status = "";

       //不同的subject_type,传入的类型参数不通，ex:book,读过:readed 电影:watched..
       if(statusID == _subjectModifyReadedRadio.getId()){
           if(_subject_type.equals(Assistant.STATUS_MOVICE)){
               status = Assistant.STATUS_MOVICE_WATCHED;
           }else if(_subject_type.equals(Assistant.STATUS_MUSIC)){
               status = Assistant.STATUS_MUSIC_LISTENED;
           }else{
               status = Assistant.STATUS_BOOK_READED;
           }
       }else if(statusID == _subjectModifyReadingRadio.getId()){
           if(_subject_type.endsWith(Assistant.STATUS_MUSIC))
               status = Assistant.STATUS_MUSIC_LINSTENING;
           else
               status = Assistant.STATUS_BOOK_READING;
       }else{
           //想看，想读，想听 都是同一个值 wish
           status = Assistant.STATUS_BOOK_WISH;
       }

        _subjectUpdateCollectionBtn.setEnabled(false);
       _subjectUpdateCollectionBtn.setText(getString(R.string.saving));

        //First collection
        if(_collectionRecord ==null ||_collectionRecord.collectionEntry==null){

            createCollection();
            return;
        }


       _thread.startThreadUpdateSubjectCollection(_handler,
               _collectionRecord.collectionEntry,status,tags,
               (int)_subjectModifyRating.getRating(),summary);


    }

    private void createCollection(){
              String[] tempTag = _subjectModifyTags.getText().toString().split(" ");
            List<Tag> tagList = new ArrayList<Tag>();
              //格式化tags字符串, 过滤为空的字符串
            for(String s:tempTag){
                if(s!=null&& !s.equals("")){
                    Tag tag = new Tag();
                    tag.setName(s);
                    tagList.add(tag);
                }
            }

        String status = Assistant.STATUS_BOOK_WISH;

        if(_subjectModifyReadedRadio.isChecked()){
            if(_subject_type.equals(Assistant.STATUS_BOOK))
                status = Assistant.STATUS_BOOK_READED;
            if(_subject_type.equals(Assistant.STATUS_MOVICE))
                status = Assistant.STATUS_MOVICE_WATCHED;
            if(_subject_type.equals(Assistant.STATUS_MUSIC))
                status = Assistant.STATUS_MUSIC_LISTENED;
        }else if(_subjectModifyReadingRadio.isChecked()){
            if(_subject_type.equals(Assistant.STATUS_BOOK))
                status = Assistant.STATUS_BOOK_READING;
            if(_subject_type.equals(Assistant.STATUS_MUSIC))
                status = Assistant.STATUS_MUSIC_LINSTENING;
        }

            Rating myrating = new Rating();
            myrating.setValue((int)_subjectModifyRating.getRating());

            _subjectUpdateCollectionBtn.setText(getString(R.string.saving));
            _subjectUpdateCollectionBtn.setEnabled(false);
            _thread.startThreadCreateCollection(_handler,this,new Status(status),
                      tagList,_subject_modify_summary.getText().toString(),
                      _subjectRecord.subjectEntry,myrating);
    }

    /**
     * 接受的线程返回处理:
     *  1.加载条目数据成功
     *  2.加载条目数据失败
     *  3.加载条目封面图片成功
     *  4.加载条目封面图片失败
     *  5.推荐条目到豆瓣成功
     *  6.推荐条目到豆瓣失败
     *  7.获取评论数据成功
     *  8.获取评论数据失败
     */
    private Handler _handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Assistant.FETCH_SUBJECT_DONE:          //加载条目成功
                    Bundle bundle = msg.getData();
                    SubjectRecord sr = (SubjectRecord) bundle.
                            getSerializable(Assistant.KEY_OF_SUBJECT);
                    updateView(sr);
                    _thread.startThreadImageDownload(Assistant.STATUS_BOOK_READED,
                            sr.icon_url.replaceAll("spic","lpic"), _handler, 1);
                    break;
                case Assistant.FETCH_SUBJECT_FAIL:          //加载条目失败
                    //TODO :do something...
                    break;
                case Assistant.FETCH_BOOK_READED_IMAGE_DONE://加载封面图片成功
                    Bundle ble = msg.getData();
                    ThreadTool.ImageSerialz imgs =
                            (ThreadTool.ImageSerialz) ble.getSerializable(
                                    Assistant.THREAD_IMAGE_KEY);
                    //   imgs.m_bitmap = createZoomImage(imgs.m_bitmap,2);
                    imgs.m_bitmap = createReflectedImage(imgs.m_bitmap);
                    _coverImage.setImageBitmap(imgs.m_bitmap);
                    break;
                case Assistant.FETCH_BOOK_READED_IMAGE_FAIL://加载封面图片失败
                    break;
                case Assistant.FETCH_RECOMMEND_PUBLISH_DONE://推荐条目成功
                    _recommendBtn.setEnabled(true);
                    _recommendBtn.setText("推荐到豆瓣");
                    PopupRecommend pr = new PopupRecommend(CollectionSubjectActivity.this);
                    pr.showToastWindow(1,"推荐成功");
                     break;
                case Assistant.FETCH_RECOMMEND_PUBLISH_FAIL://推荐条目失败
                    _recommendBtn.setEnabled(true);
                    _recommendBtn.setText("推荐到豆瓣");
                    break;
                case Assistant.FETCH_SUBJECT_REVIEW_DONE:   //加载条目评论成功
                    Bundle commentBundle =msg.getData();
                    BundleSerializable bs = (BundleSerializable)
                            commentBundle.getSerializable(Assistant.KEY_OF_SUBJECT_REVIEW);
                    updateReviews(bs.rrs);

                    //判断是否还有更多的评论还未加载出来
                    if(bs.rrs.size()>0 &&
                            _subjectReviewLay.getChildCount()< bs.rrs.get(0).totalResult){
                        _subjectLoadReviewBtn.setText("加载更多评论");
                    }else{
                        _subjectLoadReviewBtn.setVisibility(View.GONE);
                    }
                    _subjectReviewCount = _subjectReviewLay.getChildCount()+1;
                    break;
                case Assistant.FETCH_SUBJECT_REVIEW_FAIL:   //加载条目评论失败
                    PopupRecommend prs =
                            new PopupRecommend(CollectionSubjectActivity.this);
                    prs.showToastWindow(0,"加载评论失败");

                    break;
                case Assistant.FETCH_REVIEW_AVATAR_DONE:    //加载评论头像成功
                    Bundle bundleAvatar = msg.getData();
                    BundleSerializable bsAvatar =  (BundleSerializable)
                            bundleAvatar.getSerializable(Assistant.KEY_OF_IMAGE);

                    updateReviewAvatar(bsAvatar.reviewAvatars);
                    break;
                case Assistant.FETCH_USER_COLLECTION_DONE:  //加载用户收藏记录成功
                    Bundle bundleCollection = msg.getData();
                    _collectionRecord = (CollectionRecord)
                            bundleCollection.getSerializable(Assistant.KEY_OF_COLLECTION);
                    updateCollectionView();
                    break;
                case Assistant.FETCH_USER_COLLECTION_FAIL:  //加载用户收藏记录失败
                    break;

                case Assistant.FETCH_UPDATE_COLLECTION_DONE:
                    _subjectUpdateCollectionBtn.setEnabled(true);
                    _popupRecommend.showToastWindow(1,getString(R.string.update_success));
                    _subjectUpdateCollectionBtn.setText(getString(R.string.save));
                    break;
                case Assistant.FETCH_UPDATE_COLLECTION_FAIL:
                    _subjectUpdateCollectionBtn.setEnabled(true);
                    _subjectUpdateCollectionBtn.setText(getString(R.string.save));
                    _popupRecommend.showToastWindow(0,getString(R.string.update_fail));
                    break;

                case Assistant.FETCH_CREATE_COLLECTION_DONE:
                    _subjectUpdateCollectionBtn.setText(getString(R.string.save));
                    _popupRecommend.showToastWindow(1,getString(R.string.create_success));
                    break;
                case Assistant.FETCH_CREATE_COLLECTION_FAIL:
                    _subjectUpdateCollectionBtn.setText(getString(R.string.save));
                    _popupRecommend.showToastWindow(0,getString(R.string.create_fail));
                    break;
                case Assistant.FETCH_PUBLISH_REVIEW_DONE:
                    _popupRecommend.showToastWindow(1,getString(R.string.publish_success));
                    _subjectPublishReviewBtn.setText(getString(R.string.publish_new_review));
                    break;
                case Assistant.FETCH_PUBLISH_REVIEW_FAIL:
                    _popupRecommend.showToastWindow(0,getString(R.string.publish_fail));
                    _subjectPublishReviewBtn.setText(getString(R.string.publish_new_review));
                    break;
                default:
                    break;
            }
        }

        //TODO: 1.FETCH_BOOK_READED_IMAGE_DONE 常量名应该修改
        //TODO: 2.接口数据返回失败 错误处理
        //TODO：3.字符串写入到String.xml中
    };

    /**
     * 线程请求数据返回成功后，更新视图,如果是从用户的收藏列表进入的则直接利用列表的
     * CollectionRecord对象，给评价数据赋值，没有则开线程加载
     * @param sr
     */
    private void updateView(SubjectRecord sr) {

        findViewById(R.id.rightPanel).setVisibility(View.VISIBLE);
        _progressLay.setVisibility(View.GONE);
        _subjectContentLay.setVisibility(View.VISIBLE);

        _subjectRecord = sr;

        _titleTx.setText(sr.title);
        _ratingbar.setRating(sr.rating_average / 2);

        _rating_average.setText("" + sr.rating_average);
        _rating_num.setText("(已有" + sr.rating_numRatess + "人评价)");

        //内容简介
        _cotentSummary.setText((sr.summary != null) ? sr.summary : "暂无简介");

        HashMap<String,String> newAttrMap = new HashMap<String,String>();
        for(Attribute ai:sr.attributes){
            if(newAttrMap.get(ai.getName()) == null && !ai.getName().equals("track")){
                for(Attribute attribute:sr.attributes){

                    if(attribute.getName().equals(ai.getName())){
                        if(newAttrMap.get(ai.getName())==null)
                        newAttrMap.put(ai.getName(),ai.getContent());
                        else{
                           String content = newAttrMap.get(attribute.getName());
                            content = content+"/"+attribute.getContent();
                            newAttrMap.remove(attribute.getName());
                            newAttrMap.put(attribute.getName(),content);
                        }

                    }
                }
            }
        }

        Iterator iterator = newAttrMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            addAttributeTextView(entry.getKey().toString(),entry.getValue().toString(),1);
        }


        addTagTextView(sr.tags);

//        if(_collectionRecord != null){
//           _subjectMyRating.setRating(_collectionRecord.rating);
//            String desc = Assistant.SUBJECT_RATING_DESC.get(_collectionRecord.rating);
//           _subjectMyRatingDescTx.setText(desc);
//        }else{
//            _subjectMyRating.setVisibility(View.GONE);
//            _subjectMyRatingTextTx.setVisibility(View.GONE);
//            _subjectMyRatingDescTx.setVisibility(View.GONE);
//        }

        //view加载完后，自动开始加载评论,更多的评论需要用户手动点击加载
        _thread.startThreadFetchSubjectReviews(_handler,_subjectRecord.id,
                                        _subjectReviewCount,_subject_type);

        //view加载完后,根据sujectEnety返回的 Link 值判断用户是否收藏了改条目,如果有
        //则加载收藏数据显示,如果没有则让用户默认添加
        if( sr.collection_url != null)
         _thread.startThreadFetchSubjectCollection(_handler,sr.collection_url);




        updateCollectionTag();
    }

    /**
     * 添加属性条目文本到指定的LinearLayout布局中，纵向排列
     * @param name
     * @param content
     * @param position
     */
    private void addAttributeTextView(String name, final String content, int position) {

        //过滤不需要显示的标签
        if(name.equals("imdb") || name.equals("website") || name.equals("year"))
        return;

        TextView textView = new TextView(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(240,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(params);

        //作者简介被单独提取出来，在下方分段显示
        if (name.equals("author-intro")) {
            _authorSummary.setText(content);
            return;
        }

        if(name.equals("tracks")){
            TextView trackText = (TextView)findViewById(R.id.subject_item_author);
            trackText.setText("曲目:");
            _authorSummary.setText(content);
            return;
        }

        if(name.equals("cast")){
            TextView trackText = (TextView)findViewById(R.id.subject_item_author);
            trackText.setText("主演:");
            _authorSummary.setText(content);

            TextView juqinText = (TextView)findViewById(R.id.subject_item_detai);
            juqinText.setText("剧情介绍:");
            return;
        }

        if(name.equals("radio_url") && content!=null && !content.equals("")){

              //如果是音乐，显示豆瓣 FM链接
        if(_subject_type.equals(Assistant.STATUS_MUSIC)){
            _fmLay = (LinearLayout)findViewById(R.id.fm_lay);
            _fmText = (TextView)findViewById(R.id.fm_text);
            _fmLay.setVisibility(View.VISIBLE);
            _fmText.setText("正在播放《"+_subjectRecord.title+"》");

        }

         _fmLay = (LinearLayout)findViewById(R.id.fm_lay);
         _fmLay.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                   Uri uri = Uri.parse(content);
                   Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                   startActivity(intent);
                }
            });
           return;
        }

        name = Assistant.SUBJECT_BOOK_MAP.get(name);
        String text = name + content;

        textView.setText(text, TextView.BufferType.SPANNABLE);

        Spannable sp = (Spannable) textView.getText();

        // 截取TextView文本，属性值显示不同的颜色
        if (sp != null && name != null) {
            sp.setSpan(new ForegroundColorSpan(Color.BLACK), name.length(), text.length(),
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            textView.setText(sp);
        }

        textView.setTextSize(14);
        _attributeLay.addView(textView);

        //TODO：1.是否要对所有的attribute的位置重新排列，接口返回的attribute无序
    }

    /**
     * 添加条目标签到指定的tag LinearLayout布局中,横向排列
     * @param tags
     */
    private void addTagTextView(List<Tag> tags) {

        LinearLayout tagsLay = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        tagsLay.setOrientation(LinearLayout.HORIZONTAL);

        //tagsLay.setLayoutParams();

        int tagCount = 0;
        int position = 0;
        int tagWidth = 0;
        for(Tag t:tags){

            if(tagCount>20 ){
                tagCount = 0;
                tagWidth = 0;
                _tagsLay.addView(tagsLay);
                tagsLay = null;
                tagsLay = new LinearLayout(this);
                tagsLay.setOrientation(LinearLayout.HORIZONTAL);
                tagsLay.setLayoutParams(params);
            }

            String text = t.getName() + "(" + t.getCount() + ")  ";
            tagCount = tagCount+text.length();

            TextView textView = new TextView(this);
            textView.setTextColor(Color.BLACK);
            textView.setText(text, TextView.BufferType.SPANNABLE);

            Spannable sp = (Spannable) textView.getText();
            if (sp != null) {
                sp.setSpan(new ForegroundColorSpan(Color.BLUE), t.getName().length() + 1,
                    text.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                textView.setText(sp);
            }
            int textViewWidth = textView.getWidth();
            tagWidth = textViewWidth+tagWidth;
            textView.setTextSize(14);
            position++;
            tagsLay.addView(textView);
        }


        _tagsLay.addView(tagsLay);
        //TODO :由于线性布局不会自动换行，所有多个标签超过一行格式将错乱,更好的方式 显示所有标签
        //TODO :所有标签放在同一个tetview中，但是无法高亮显示标签数
    }

    /**
     * 当点击确定发布推荐时，从PopupRecommend 回调callBack，并传回参数
     * 开启线程发布本次推荐，线程加载中在推荐按钮处显示滚动
     *
     * @see PopupRecommend
     * @param recommednText
     */
    @Override
    public void callBack(String recommednText) {
         String url = "http://api.douban.com/"+_subject_type+"/subject/"+_id;
        _thread.startThreadPublishSubjectRecommand(recommednText,url,_handler);
        _recommendBtn.setEnabled(false);
        _recommendBtn.setText("正在提交..");

        //TODO :字符串 写入String.xml
    }

    @Override
    public void pubishReviewCallBack(String title,String content,int rating){
        _subjectPublishReviewBtn.setText("正在提交");
        _thread.startThreadPublishReview(_handler, title, content, rating,
                _subjectRecord.subjectEntry);
    }

    /**
     * 更新评价视图
     */
    public void updateCollectionView(){

        _subjectModifyRating.setRating(_collectionRecord.rating);

        String tag_str = "";
        if(_collectionRecord.tags!=null && _collectionRecord.tags.size()>0){
            for(String tag:_collectionRecord.tags){
                tag_str = tag_str+" "+tag;
            }
        }
        _subjectModifyTags.setText(tag_str);
        _subject_modify_summary.setText(_collectionRecord.summary);

         if(_collectionRecord.status.equals(Assistant.STATUS_BOOK_READING)||
           _collectionRecord.status.equals(Assistant.STATUS_MUSIC_LINSTENING)){
            _subjectModifyReadingRadio.setChecked(true);
        }else if(_collectionRecord.status.equals(Assistant.STATUS_BOOK_WISH) ||
                _collectionRecord.status.equals(Assistant.STATUS_MOVICE_WISH)){
            _subjectModifyWishRadio.setChecked(true);
        }else{
            _subjectModifyReadedRadio.setChecked(true);
        }

    }

    public void updateCollectionTag(){

        LinearLayout maybeTagsLay = (LinearLayout)findViewById(
                                            R.id.subject_modify_maybe_tags_lay);
        String maybeTags = "";
        for (Tag tag:_subjectRecord.tags){
            maybeTags += tag.getName();
        }

         String myTags ="";
        if(_collectionRecord!=null && _collectionRecord.tags!= null){
            for(String s:_collectionRecord.tags){
                myTags += s+" ";
            }
        }

        _subjectModifyTags.setText(myTags);

        LinearLayout cellLayout = new LinearLayout(this);
        LinearLayout.LayoutParams  params= new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        cellLayout.setOrientation(LinearLayout.HORIZONTAL);
        cellLayout.setLayoutParams(params);

        int cellCount = 10;
        int nowCount = 0;
        int position = 0;
        for(final Tag tag:_subjectRecord.tags){
           //一行 标签的字符串不得超过10个，每行不能显示 4个button，以免超过一行
            if(nowCount >= cellCount || position%5==0 ){
                nowCount = 0;
                position = 0;
                maybeTagsLay.addView(cellLayout);
                cellLayout = null;
                cellLayout = new LinearLayout(this);
                cellLayout.setLayoutParams(params);
            }

             final ToggleButton button =new ToggleButton(this);
            button.setText(tag.getName());
            button.setTextOff(tag.getName());
            button.setTextOn(tag.getName());
            nowCount += tag.getName().length();
            position ++;
             button.setOnClickListener( new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                     if(replaeTag(tag.getName())){

                         button.setChecked(true);
                     }else{
                         button.setChecked(false);
                     }

                }
            });
            cellLayout.addView(button);
        }
        maybeTagsLay.addView(cellLayout);
    }

    public Boolean replaeTag(String str){
        Boolean result = false;
        String tags=_subjectModifyTags.getText().toString();
        String newStr="";

        //Format
        String[] newStrArr = tags.split(" ");
        ArrayList<String> otherStrArr = new ArrayList<String>();

        if(newStrArr.length == 1 && newStrArr[0].equals("")){
            _subjectModifyTags.setText(str+" ");
            return true;
        }

        for(String s:newStrArr){
            if(s.equals(str)){
                result = true;
                continue;
            }

            if(!s.equals("") && s!=""){
              //  newStr += s+" ";
                otherStrArr.add(s);
            }
        }

        for(String s:otherStrArr){
            newStr += s+" ";
        }

        if(result){
           _subjectModifyTags.setText(newStr);
            return false;
        }else{
            _subjectModifyTags.setText(newStr+" "+str);
            return true;
        }


//        if(newStr.indexOf(str)>0){
//            newStr = newStr.replaceAll(str,"");
//        }else{
//            result =true;
//            newStr = newStr+" "+str;
//        }

    }

    /**
     * 更新评论视图，开启评论头像线程
     * @param reviewRecords
     */
    public void updateReviews(ArrayList<ReviewRecord> reviewRecords){
        if(_reviewsList!=null)
            _reviewsList.addAll(reviewRecords);
        else
            _reviewsList = reviewRecords;

        String[] avatar_url = new String[reviewRecords.size()];
        int i = 0;
        for(ReviewRecord rr:reviewRecords){
            addReviewViewToLayout(rr);
            avatar_url[i] = rr.avatar_url;
            i++;
        }

        //一次性载入评论所有头像
        _thread.startThreadFetchReviewAvatar(_handler, avatar_url, this);
    }

    /**
     * 添加评论视图，绘制评论所需要的组件和特殊标签事件
     * @param rr
     */
    private void addReviewViewToLayout(ReviewRecord rr){
       View view =  _inflater.inflate(R.layout.review_item,null);
       TextView titleView = (TextView)view.findViewById(R.id.review_title);
       TextView summaryView = (TextView)view.findViewById(R.id.review_summary);
       TextView dataView = (TextView)view.findViewById(R.id.review_date);
       TextView userNameView = (TextView)view.findViewById(R.id.review_user_name);
       RatingBar rating = (RatingBar)view.findViewById(R.id.review_rating);
       TextView digTextView = (TextView)view.findViewById(R.id.review_dig);
       ImageView avatarImage = (ImageView)view.findViewById(R.id.review_user_avatar);

        _subjectReviewAvatarImageView.add(avatarImage);

       rating.setRating(rr.rating);
        titleView.setText(rr.title);

        //添加a标签是为了。让URLSpan 能够识别
        summaryView.setText(Html.fromHtml(rr.summary+"<a href=\"www\">全部</a>"));

        digTextView.setText(""+rr.dig+"人觉得有用");

        String date[] = rr.updateDate.split(" ");

        dataView.setText(date[0]);
        userNameView.setText(rr.author);


        summaryView.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence text =summaryView.getText();

        if(text instanceof Spannable){
            //在评论尾端加入支持点击事件的文本
            Spannable sp = (Spannable)summaryView.getText();
            URLSpan[] urls = sp.getSpans(0, text.length(), URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();

            for(URLSpan s:urls){
                MyURLSpan myURLSpan =new MyURLSpan(rr.reviewId,rr,(_subjectReviewAvatarImageView.size()-1));
                style.setSpan(myURLSpan,sp.getSpanStart(s),sp.getSpanEnd(s),
                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            summaryView.setText(style);
        }

        _subjectReviewLay.addView(view);

    }

    /**
     *
     * @param avatars
     */
    public void updateReviewAvatar(ArrayList<Bitmap> avatars){
        int i=0;
        for(Bitmap bitmap:avatars){
            _subjectReviewAvatarBitmap.add(bitmap);

        }

        for (ImageView imageView:_subjectReviewAvatarImageView){

            if(_subjectReviewAvatarBitmap.size()>i&& _subjectReviewAvatarBitmap.get(i)!=null)
            imageView.setImageBitmap(_subjectReviewAvatarBitmap.get(i));
            i++;
        }
    }


    /**
     * 自定义的USLSPan子类，用来扑获超链接文本的点击事件
     */
    private  class MyURLSpan extends ClickableSpan {
        private String str;
        private ReviewRecord reviewRecord;
        private int position;

        public MyURLSpan(String str,ReviewRecord reviewRecord,int position){
            this.str = str;
            this.reviewRecord = reviewRecord;
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            Bitmap bitmap = null;
            if(_subjectReviewAvatarBitmap != null && _subjectReviewAvatarBitmap.size()!=0 &&
                    _subjectReviewAvatarBitmap.size()>position &&
                    _subjectReviewAvatarBitmap.get(position) !=null){
                bitmap = _subjectReviewAvatarBitmap.get(position);
            }else{
                bitmap = BitmapFactory.decodeResource(getResources(),
                                        R.drawable.default_icon_48_48);
            }

            _popupRecommend.showWindowReviewFull(str,
                    CollectionSubjectActivity.this,reviewRecord,bitmap);
        }
    }

    //------------------------------PUBLIC METHOD---------------------------
    //TODO:以下公用方法独立出来


    /**
     * 创建图片倒影效果
     * @param originalImage
     * @return
     */
    public  Bitmap createReflectedImage(Bitmap originalImage) throws OutOfMemoryError {
        // The gap we want between the reflection and the original default_bg_image
        final int reflectionGap = 1;

        if(originalImage == null)
            return null;

        originalImage = zoomBitmap(originalImage);


        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        // This will not scale but will flip on the Y axis
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

        // Create a Bitmap with the flip matrix applied to it.
        // We only want the bottom half of the default_bg_image
        Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
                height / 2, width, height / 2, matrix, false);

        // Create a new bitmap with same width but taller to fit reflection
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                (height + height / 2), Bitmap.Config.ARGB_8888);

        // Create a new Canvas with the bitmap that's big enough for
        // the default_bg_image plus gap plus reflection
        Canvas canvas = new Canvas(bitmapWithReflection);
        // Draw in the original default_bg_image
        canvas.drawBitmap(originalImage, 0, 0, null);
        // Draw in the gap
        Paint defaultPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
        // Draw in the reflection
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

        // Create a shader that is a linear gradient that covers the reflection
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0,
                originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
                        + reflectionGap, 0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);
        // Set the paint to use this shader (linear gradient)
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                + reflectionGap, paint);

        return bitmapWithReflection;
    }


    public Bitmap zoomBitmap(Bitmap bitmap){
           int width = bitmap.getWidth();
           int height = bitmap.getHeight();

        if(width<300 && height<400)
            return bitmap;

        Matrix matrix = new Matrix();
        matrix.postScale(0.5f,0.5f);

        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
        return resizeBitmap;
    }

      @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }

}